package com.songyang.blog.config;

import cn.hutool.core.map.MapUtil;
import com.songyang.blog.shiro.AccountRealm;
import com.songyang.blog.shiro.AuthFilter;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {
    @Autowired
    AccountRealm accountRealm;

    @Bean//创建过滤工厂Bean
    public DefaultWebSecurityManager securityManager(AccountRealm accountRealm) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(accountRealm);
        return securityManager;
    }

    //创建过滤器链
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(DefaultWebSecurityManager defaultWebSecurityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);//把得到的securityManager传进去,设置安全管理器
        shiroFilterFactoryBean.setLoginUrl("/login");//s设置登录的url
        shiroFilterFactoryBean.setSuccessUrl("/");
        shiroFilterFactoryBean.setUnauthorizedUrl("/error/403");
        shiroFilterFactoryBean.setFilters(MapUtil.of("auth", authFilter()));

        Map<String, String> filterMap = new LinkedHashMap<>();
        /*
        anon:无需认证就可以直接访问
        authc：必须认证了才能访问
        user:必须拥有"记住我"才可以访问
        perms:拥有对某个资源的权限才可以访问
        role:拥有某个角色权限才可以使用
         */
        // filterMap.put("/**", "authc");
        filterMap.put("/static/**", "anon");//这里支持通配符，注意，*代表当前的目录所有文件，**代表这个目录下面的所有文件
        //  filterMap.put("/static/**", "anon");//这里支持通配符，注意，*代表当前的目录所有文件，**代表这个目录下面的所有文件
        filterMap.put("/user/home", "auth");
        filterMap.put("/user/set", "auth");
        filterMap.put("/user/upload", "auth");
        filterMap.put("/user/index", "auth");
        filterMap.put("/user/public", "auth");
        filterMap.put("/user/collection", "auth");
        filterMap.put("/user/mess", "auth");
        filterMap.put("/msg/remove/", "auth");
        filterMap.put("/message/nums/", "auth");

        filterMap.put("/collection/remove/", "auth");
        filterMap.put("/collection/find/", "auth");
        filterMap.put("/collection/add/", "auth");

        filterMap.put("/post/edit", "auth");
        filterMap.put("/post/submit", "auth");
        filterMap.put("/post/delete", "auth");
        filterMap.put("/post/reply/", "auth");

        filterMap.put("/websocket", "anon");
        filterMap.put("/login", "anon");

        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterMap);
        return shiroFilterFactoryBean;
    }

    @Bean
    public AuthFilter authFilter() {
        return new AuthFilter();
    }

}
